package com.kedacom.demo.cometd;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.cometd.bayeux.MarkedReference;
import org.cometd.bayeux.server.BayeuxServer;
import org.cometd.bayeux.server.ConfigurableServerChannel;
import org.cometd.bayeux.server.ServerChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

/**
 * ChannelService
 * @author luocanfeng
 * @date 2016年4月15日
 */
@Service
public class ChannelService {

	private Logger logger = LoggerFactory.getLogger(getClass());

	@Resource
	private BayeuxServer bayeuxServer;

	@PostConstruct
	public void init() {
		this.createChannelIfAbsent("/demo");
		this.createChannelIfAbsent("/meeting/12345");
	}

	/**
	 * 创建持久化的Channel
	 */
	public ServerChannel createChannelIfAbsent(String channelId) {
		MarkedReference<ServerChannel> ref = bayeuxServer.createChannelIfAbsent(channelId,
				new ServerChannel.Initializer() {

					public void configureChannel(ConfigurableServerChannel channel) {
						channel.setPersistent(true);
						logger.debug("Channel {} created.", channel.getId());
					}
				});
		return ref.getReference();
	}

	/**
	 * 根据channelId获取Channel
	 */
	public ServerChannel getChannel(String channelId) {
		return bayeuxServer.getChannel(channelId);
	}

	/**
	 * 删除Channel
	 */
	public void removeChannel(String channelId) {
		ServerChannel channel = this.getChannel(channelId);
		if (channel != null) {
			channel.remove();
		}
	}

}
